package cn.sc.allinpay.allfavour.business.login;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;

import com.alibaba.fastjson.JSON;
import com.allinpay.usdk.core.data.ResponseData;

import cn.pai.mvp.callback.MpCallBack;
import cn.pai.mvp.intervenor.Intervenor;
import cn.pai.mvp.presenter.PaiPresenter;
import cn.sc.allinpay.allfavour.app.Constant;
import cn.sc.allinpay.allfavour.business.common.data.CashierData;
import cn.sc.allinpay.allfavour.business.common.data.ConfigData;
import cn.sc.allinpay.allfavour.business.common.data.PosInfo;
import cn.sc.allinpay.allfavour.business.common.data.UserInfo;
import cn.sc.allinpay.allfavour.business.common.utils.SpUtils;
import cn.sc.allinpay.allfavour.business.main.MainActivity;
import cn.sc.allinpay.allfavour.business.setconfig.SetConfigActivity;
import cn.sc.allinpay.allfavour.module.allin.AllinUtils;

/**
 * 登录 presenter
 * author：pany
 * on 2017/12/1 11:27
 */
public class LoginPresenter extends PaiPresenter<LoginContract.View> implements LoginContract.Presenter {
    public static final int REQ_SIGN = 0x01;
    public static final int REQ_CONFIG = 0x02;
    private LoginModel model = new LoginModel();

    @Override
    protected Intervenor createIntervenor() {
        return new Intervenor() {
            @Override
            public void onActivityResult(int requestCode, int resultCode, Intent data) {
                super.onActivityResult(requestCode, resultCode, data);
                    if (data != null && data.getExtras() != null) {
                        Bundle extras = data.getExtras();
                        ResponseData result = (ResponseData) extras.getSerializable("RESPONSE");
                        if (result != null) {
                            try {
                                if (result.getValue("REJCODE").equals("00")) {
                                    if (requestCode == REQ_SIGN) {
                                        //POS配置参数
                                        ConfigData configData = model.getGlobal().getConfigData();
                                        if (configData == null) {
                                            configData = new ConfigData();
                                        }
                                        if (TextUtils.isEmpty(configData.getMerName())) {
                                            configData.setMerName(result.getValue("MERCH_NAME"));//万商惠商户名称
                                        }
                                        configData.setTermNo(result.getValue("SN"));//终端号序列号
//                                    configData.setBrchNo(data.getStringExtra("brchNo"));//机构号:USDK 获取不到
//                                    configData.setStoreNo(data.getStringExtra("yxstrore")); // 门店号: USDK 获取不到
                                        if (TextUtils.isEmpty(configData.getTerId())) {
                                            configData.setTerId(result.getValue("TER_ID"));//终端号
                                        }
//                                    String vouchIp = data.getStringExtra("voucherHostIp");
//                                    String vouchPort = data.getStringExtra("voucherHostPort");
//                                    configData.setIP(vouchIp);
//                                    configData.setPORT(vouchPort);
//                                    StringBuffer url = new StringBuffer();
//                                    url.append("http://").append(vouchIp).append(":").
//                                            append(vouchPort).append("/wsh-oil-api/pos/");
//                                    configData.setBASEURL(url.toString());//基本通信地址
//                                    configData.setBRCHKEY(data.getStringExtra("MD5key"));//万商惠分配的机构密钥明文
//                                    configData.setTEMPKEY1(data.getStringExtra("TempKey1"));//修改收银员密码的秘钥1
//                                    configData.setTEMPKEY2(data.getStringExtra("TempKey2"));//修改收银员密码的秘钥2
                                        configData.setOperatorId("01");//操作员
                                        PosInfo posInfo = new PosInfo();
                                        posInfo.setTermNo(result.getValue("SN"));//终端号序列号
                                        posInfo.setMer_id(result.getValue("MERCH_ID"));//商户号
                                        posInfo.setMer_name(result.getValue("MERCH_NAME"));//商户名称
                                        posInfo.setTer_id(result.getValue("TER_ID"));//终端号
                                        posInfo.setOperator_id("01");//操作员号
                                        //登录成功后，登录信息保存到缓存和文件中
                                        model.getGlobal().setConfigData(configData);//万商惠参数
                                        model.getGlobal().setPosInfo(posInfo);//收银宝参数
                                        SpUtils.put(view.getContext(), Constant.SPNAME, Constant.SpKey.ConfigData, JSON.toJSONString(configData));
                                        SpUtils.put(view.getContext(), Constant.SPNAME, Constant.SpKey.PosInfo, JSON.toJSONString(posInfo));

                                        //未配置万商惠信息进入配置界面
                                        ConfigData configData1 = model.getGlobal().getConfigData();
                                        if (configData1 == null || (configData1 != null && (configData1.getMerName() == null || configData1.getBrchNo() == null || configData1.getTerId() == null || configData1.getIP() == null || configData1.getPORT() == null
                                                || configData1.getBRCHKEY() == null || configData1.getTEMPKEY1() == null || configData1.getTEMPKEY2() == null || configData1.getSpOrgNo() == null || configData1.getSpUserName() == null || configData1.getSpPwd() == null))  ) {
                                            goSetConfig();
                                        } else {
                                            reqLogin();
                                        }
                                    }
                                } else {
                                    String error = result.getValue("REJCODE");
                                    view.toast(error);
                                }
                            } catch (Throwable t) {
                                Log.e("uDemo", "Could not parse malformed JSON: \"" + result + "\"");
                            }
                        }
                    }
                }

        };
    }

    @Override
    public void start() {

    }

    @Override
    public void callSign() {
        String name = view.getUserName();
        String pwd = view.getPassword();
        if (TextUtils.isEmpty(name)) {
            view.prompt("用户名不能为空");
            return;
        }
        if (TextUtils.isEmpty(pwd)) {
            view.prompt("用户密码不能为空");
            return;
        }
        if ("99".equals(name)) {
            if (Constant.MANAGER_PWD_99.equals(pwd)) {
                view.toActivity(SetConfigActivity.class, null);
            } else {
                view.prompt("管理员密码错误");
            }
            return;
        }
        //判断是否存在 USDK
        if (AllinUtils.isAppExit(view.getContext())) {
            AllinUtils.callSign(view.getActivity(), REQ_SIGN);
        } else {
            view.prompt("请安装并配置 USDK 后使用");
        }
    }

    @Override
    public void goSetConfig() {
        ConfigData configData = model.getGlobal().getConfigData();
        if (configData == null) {
            if (AllinUtils.isAppExit(view.getContext())) {
                AllinUtils.callSign(view.getActivity(), REQ_SIGN);
            } else {
                view.prompt("请安装并配置 USDK 后使用");
            }
            return;
        }
        view.toActivity(SetConfigActivity.class, null);
    }

    private void reqLogin() {
        view.loading("登录中...");
        model.reqLogin(view.getUserName(), view.getPassword(), new MpCallBack<CashierData, String>() {
            @Override
            public void onSuccess(CashierData cashierData) {
                //登录成功后，登录信息保存到缓存和文件中
                model.getGlobal().setCashierData(cashierData);
                SpUtils.put(view.getContext(), Constant.SPNAME, Constant.SpKey.CashierData, JSON.toJSONString(cashierData));
                ConfigData configData = model.getGlobal().getConfigData();
                model.posLogin(configData.getSpOrgNo(), configData.getSpUserName(), configData.getSpPwd(), configData.getTermNo(), configData.getTerId(), new MpCallBack<UserInfo, String>() {
                    @Override
                    public void onSuccess(UserInfo userInfo) {
                        if (view == null) {
                            return;
                        }
                        model.getGlobal().setUserInfo(userInfo);
                        SpUtils.put(view.getContext(), Constant.SPNAME, Constant.SpKey.UserIfo, JSON.toJSONString(userInfo));
                        view.loaded();
                        view.toast("签到成功");
                        view.toActivity(MainActivity.class, null);
                        view.finish();
                        AllinUtils.configUSDK(view.getActivity(), REQ_CONFIG);
                    }
                    @Override
                    public void onFailure(String resp, String message) {
                        if (view == null) {
                            return;
                        }
                        view.loaded();
                        view.prompt(message);
                    }
                });

            }

            @Override
            public void onFailure(String response, String message) {
                view.loaded();
                view.prompt(message);
            }
        });
    }
}
